<template>
  <el-form ref="form" :rules="rules" :model="pwd" :hide-required-asterisk="true">
    <el-form-item label="旧密码" prop="old">
      <el-input v-model.trim="pwd.old" type="password" />
    </el-form-item>
    <el-form-item label="新密码" prop="new">
      <el-input v-model.trim="pwd.new" type="password" />
    </el-form-item>
    <el-form-item label="确认密码" prop="check">
      <el-input v-model.trim="pwd.check" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button :loading="loading" type="primary" @click.native.prevent="submit">确认修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    const validateNew = (rule, value, callback) => {
      if (this.pwd.old === this.pwd.new || this.pwd.old === this.pwd.check) {
        callback(new Error('新密码不能与旧密码相同'))
      } else {
        callback()
      }
    }
    const validateCheck = (rule, value, callback) => {
      if (this.pwd.new !== this.pwd.check) {
        callback(new Error('新密码和确认密码不一致'))
      } else {
        callback()
      }
    }
    return {
      pwd: {
        old: '',
        new: '',
        check: ''
      },
      rules: {
        old: [{ required: true, message: '请输入旧密码', trigger: ['blur', 'change'] }],
        new: [{ required: true, message: '请输入新密码', trigger: ['blur', 'change'] }, { validator: validateNew }],
        check: [{ required: true, message: '请输入确认密码', trigger: ['blur', 'change'] }, { validator: validateCheck }]
      },
      loading: false
    }
  },
  methods: {
    submit() {
      this.loading = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$message({
            message: '密码修改成功',
            type: 'success',
            duration: 5 * 1000
          })
        }
      })
    }
  }
}
</script>
